import { selectById } from '@/services/user';
import { Modal } from 'antd';
import MD5 from 'crypto-js/md5';
import Cookies from 'js-cookie';
import type React from 'react';

// 获取qs参数
export function getQueryParams() {
  let queryObj: RecordItem = {};
  queryObj = JSON.parse(localStorage.getItem('qs') as any);
  return queryObj || {};
}

// 背景透明度
export const colorStr = (current: number) => {
  const color = localStorage.getItem('color') || '#1a7721';

  return `rgb(${parseInt('0x' + color.slice(1, 3))},${parseInt(
    '0x' + color.slice(3, 5),
  )},${parseInt('0x' + color.slice(5, 7))}
      ,0.${current})`;
};

// 数据改变时更新qs
export const selectOne = async (role: any) => {
  const qs = getQueryParams();
  try {
    await selectById({ id: qs.id, role: role }).then((res) => {
      localStorage.setItem('qs', JSON.stringify(res));
    });
  } catch (error) {
    console.log(error);
  }
};

export const setTheme = (theme: string): void => {
  let styleLink = document.getElementById('theme-style') as HTMLLinkElement;
  const body = document.querySelector('body') as HTMLBodyElement;
  const styleSrc = `/theme/${theme}.css`;
  const bodyCls = `body-wrap-${theme}`;
  if (styleLink) {
    // 假如存在id为theme-style 的link标签，直接修改其href
    styleLink.href = styleSrc;
    body.className = bodyCls;
  } else {
    // 不存在的话，则新建一个
    styleLink = document.createElement('link');
    styleLink.type = 'text/css';
    styleLink.rel = 'stylesheet';
    styleLink.id = 'theme-style';
    styleLink.href = styleSrc;
    body.className = bodyCls;
    document.body.prepend(styleLink);
  }
};

/**
 * 保留小数位
 * @param {number} number 数值
 * @param {number} precision 保留几位小数
 */
export function toFixed(number: number, precision: number) {
  if (!number) {
    return '';
  }
  const multiplier = 10 ** (precision + 1);
  const wholeNumber = Math.floor(number * multiplier);
  const result = (Math.round(wholeNumber / 10) * 10) / multiplier;
  return Number.isInteger(result) ? result.toFixed(2) : result;
}

/**
 * 本地存储
 */
export const store = {
  get(key: string): RecordItem | string | undefined {
    const data = localStorage.getItem(MD5(key).toString());

    if (data) {
      try {
        const res = JSON.parse(data);

        return typeof res === 'number' ? data : res;
      } catch (error) {
        return data;
      }
    }

    return undefined;
  },
  set(key: string, value: any): void {
    return localStorage.setItem(
      MD5(key).toString(),
      typeof value === 'string' ? value : JSON.stringify(value),
    );
  },
  remove(key: string): void {
    return localStorage.removeItem(MD5(key).toString());
  },
  clear(): void {
    return localStorage.clear();
  },
};

/**
 * 获取本地存储中的用户信息
 */
export const getUserInfo = (): RecordItem | null => {
  const userInfo = Cookies.get('userInfo');
  return userInfo ? JSON.parse(userInfo) : null;
};

/**
 * 包装ant ant confirm
 */
export const usedConfirm = ({
  title,
  content,
  onOk,
  onCancel,
}: {
  title: string;
  content: string | React.ReactNode;
  onOk?: () => void;
  onCancel?: () => void;
}) => {
  return Modal.confirm({
    icon: null,
    title,
    content,
    cancelButtonProps: { className: 'ant-btn-gray', size: 'large' },
    okButtonProps: { className: 'ant-btn-gradient', size: 'large', loading: false },
    onOk,
    onCancel,
  });
};

/**
 * 在字符串前后补位
 * @param origin 原始字符串
 * @param length 补位后的字符串长度
 * @param value 参加补位的字符
 * @param direction 方向 前补 后补
 */
export const fillString = (
  origin: string,
  length: number,
  value: string,
  direction?: 'end' | 'start',
) => {
  if (direction === 'end') {
    return origin.padEnd(length, value);
  }
  return origin.padStart(length, value);
};

/**
 * 判断是否可以点击下一步
 */
export const compare = (_input: boolean, url: string) => {
  if (_input) {
    return url;
  }
  return '';
};

// 反转对象的key, value
export function invertKeyValues(obj: any) {
  return Object.keys(obj).reduce((acc, key) => {
    acc[obj[key]] = key;
    return acc;
  }, {});
}

/**
 * 时间戳转2020-05-07 12:00：00格式
 */

export function formatDateTime(date: any) {
  let dateNum = Number(date);
  let y = new Date(dateNum).getFullYear();
  let m: string | number = new Date(dateNum).getMonth() + 1;
  m = m < 10 ? `0${m}` : m;
  let d: string | number = new Date(dateNum).getDate();
  d = d < 10 ? `0${d}` : d;
  let h: string | number = new Date(dateNum).getHours();
  h = h < 10 ? `0${h}` : h;
  let minute: string | number = new Date(dateNum).getMinutes();
  minute = minute < 10 ? `0${minute}` : minute;
  let second: string | number = new Date(dateNum).getSeconds();
  second = second < 10 ? `0${second}` : second;
  return `${y}-${m}-${d}  ${h}:${minute}:${second}`;
}

/**
 * 获取学生填写结果
 */
export function getAnswer(sign: string) {
  return sessionStorage.getItem(sign) || '';
}

/**
 * 移除缓存中值
 */
export function removeItem(sign: string) {
  sessionStorage.removeItem(sign);
}

/**
 * 大赛评分
 */
export function Result() {}
